<div class="page-breadcrumbs">
    <ul class="breadcrumb">
        <li>
            <i class="fa fa-home"></i>
            <a href="#">Home</a>
        </li>
        <li>
            <a href="#">系统设置</a>
        </li>
        <li class="active">用户管理</li>
    </ul>
</div>
<!-- Page Body -->
<div class="page-body">
    <div class="row">
        <div class="col-lg-12 col-sm-12 col-xs-12">
            <div class="widget">
                <div class="widget-header bordered-bottom bordered-themeprimary">
                    <i class="widget-icon fa fa-tasks themeprimary"></i>
                    <span class="widget-caption themeprimary">系统用户列表</span>
                    <a id="editabledatatable_new" href="#!system/user/user-add.html" class="btn btn-sm themeprimary pull-right">新建用户</a>
                </div>
                <div class="widget-body bordered-left">
                    <div class="form-inline" role="form">
                        <div class="form-group">
                            <select class="form-control" id="userDef" data-bv-field="userDef">
                                <option value="">选择用户类型</option>
                                <option value="ADMINISTRATOR">系统管理员</option>
                                <option value="GENERAL">普通管理员</option>
                                <option value="VIP">VIP</option>
                                <option value="SVIP">SVIP</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" id="name" placeholder="姓名">
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" id="email" placeholder="邮箱">
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" id="mobile" placeholder="电话号码">
                        </div>
                        <button type="submit" class="btn btn-default" id="search">检索</button>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <div class="row">
        <div class="col-xs-12 col-md-12">
            <div class="widget">
                <div class="widget-header bordered-bottom bordered-themeprimary">
                    <i class="widget-icon fa fa-tasks themeprimary"></i>
                    <span class="widget-caption themeprimary">系统用户列表</span>
                </div>
                <div class="widget-body">
                    <table id="dt_basic" class="table table-striped table-bordered table-hover">
                        <thead>
                        <tr>
                            <th></th>
                            <th data-class="expand">用户编号</th>
                            <th data-class="expand">名称</th>
                            <th data-class="expand">昵称</th>
                            <th data-hide="phone,tablet">联系方式</th>
                            <th data-class="expand">邮箱</th>
                            <th data-class="expand">创建时间</th>
                            <th data-hide="phone">操作</th>
                        </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div id="modifyPwdDialog" style="display:none;">
        <div class="row" style="margin: 15px;">
            <form id="modifyPwdForm" name="modifyPwdForm">
                <div class="col-md-12">
                    <div class="form-group">
                        <input type="password" class="form-control" placeholder="旧密码" id="oldPwd" name="oldPwd" required="">
                    </div>
                    <div class="form-group">
                        <input type="password" class="form-control" placeholder="新密码" id="newPwd" name="newPwd" required=""
                               data-bv-notempty="true"
                               data-bv-notempty-message="新密码不能为空"
                               data-bv-identical="true"
                               data-bv-identical-field="confirmPassword"
                               data-bv-identical-message="两次输入的新密码不相同">
                    </div>
                    <div class="form-group">
                        <input type="password" class="form-control" placeholder="新密码" name="confirmPassword" required=""
                               data-bv-notempty="true"
                               data-bv-notempty-message="新密码不能为空"
                               data-bv-identical="true"
                               data-bv-identical-field="newPwd"
                               data-bv-identical-message="两次输入的新密码不相同">
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div id="modifyHptDialog" style="display:none;">
        <div class="row" style="margin: 15px;">
            <div class="col-md-12">
                <form id="modifyHptForm" name="modifyHptForm" enctype="multipart/form-data" method="post" target="ifm">
                    <div class="form-group">
                        <input type="file" class="form-control" placeholder="请选择上传文件" id="fileUpload" name="file" required="">
                    </div>
                </form>
                <iframe id='ifm' name='ifm' style="display:none"/>
            </div>
        </div>
    </div>

</div>

<script type="application/javascript">
    var oTable;
    $(function(){
        oTable = $('#dt_basic').dataTable({
            serverSide: true,
            orderMulti: false,
            "sDom": "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
            "oTableTools": {
                "aButtons": []
            },
            "language": {
                "search": "",
                'emptyTable': '没有数据',
                'loadingRecords': '加载中...',
                'processing': '查询中...',
                'sLengthMenu': '每页 _MENU_ 件',
                'zeroRecords': '没有数据',
                "oPaginate": {
                    "sPrevious": "上一页",
                    "sNext": "下一页"
                },
                //'info': '当前显示 _START_ 到 _END_ 条记录,共 _TOTAL_ 条记录,共 _PAGES_页,当前第_PAGE_ 页',
                'info': '当前显示 _START_ 到 _END_ 条记录,共 _TOTAL_ 条记录',
                'infoEmpty': '没有数据',
                'infoFiltered': '(过滤总件数 _MAX_ 条)'
            },
            columns: [
                { "data": "id" , "bSortable": false, "aTargets": [0]},
                { "data": "id" },
                { "data": "name" },
                { "data": "alias" },
                { "data": "mobile" },
                { "data": "email" },
                { "data": "createTime",
                    "render":function(data, type, full, meta){
                        return TimeUtil.yyyyMMddHHmmss(data);
                    }
                },
                { "data": "id" , "bSortable": false ,
                    "render":function(data, type, full, meta){
                        var tmp =
                                '<a href="#!system/user/user-update.html?target='+window.btoa(data)+'" class="btn btn-info btn-xs edit"><i class="fa fa-edit"></i> 修改</a> '
                                +'<a href="javascript:delData(&quot;'+window.btoa(data)+'&quot;);" class="btn btn-danger btn-xs delete"><i class="fa fa-trash-o"></i> 删除</a>'

                                +'<div class="btn-group" style="margin-left: 5px;">                                                '
                                +'	<a class="btn btn-xs btn-maroon dropdown-toggle" data-toggle="dropdown">   '
                                +'		更多 <i class="fa fa-angle-down"></i>                          '
                                +'	</a>                                                                 '
                                +'	<ul class="dropdown-menu">                                           '
                                +'		<li>                                                             '
                                +'			<a href="javascript:modifyPwdDialog(&quot;'+window.btoa(data)+'&quot;);">修改密码</a>                     '
                                +'		</li>                                                            '
                                +'		<li>                                                             '
                                +'			<a href="javascript:modifyHptDialog(&quot;'+window.btoa(data)+'&quot;);">设置头像</a>             '
                                +'		</li>                                                            '
                                +'		<li>                                                             '
                                +'			<a href="javascript:findPwd(&quot;'+window.btoa(data)+'&quot;);">找回密码</a>        '
                                +'		</li>                                                            '
                                +'		<li class="divider"></li>                                        '
                                +'		<li>                                                             '
                                +'			<a href="javascript:void(0);">设置角色</a>             '
                                +'			<a href="javascript:void(0);">设置功能</a>             '
                                +'		</li>                                                            '
                                +'	</ul>                                                                '
                                +'</div>'
                                ;
                        return tmp;
                    }
                }
            ],
            iDisplayLength:10,
            ajax: function (data, callback, settings) {
                var param = {};
                param.limit = data.length;
                param.start = data.start;
                param.page = (data.start / data.length) + 1;
                param.name = $('#name').val();
                param.email = $('#email').val();
                param.mobile = $('#mobile').val();
                param.userDef = $('#userDef').val();
                $.ajax({
                    type: "GET",
                    url: "rest/v1/sys/user/"+param.page+"/"+param.limit,
                    cache: false,
                    data: param,
                    dataType: "json",
                    success: function (content) {
                        var result = content.result;
                        if(null != content.result){
                            var returnData = {};
                            returnData.draw=result.content;
                            returnData.recordsTotal = result.totalSize;
                            returnData.recordsFiltered = result.totalSize;
                            returnData.data = result.content;
                            callback(returnData);
                        }
                    }
                });
            },
            "fnCreatedRow": function(nRow, aData, iDataIndex) {
                return $('td:eq(0)', nRow).html('<i class="fa fa-plus-square-o row-details"></i>');
            }
        });

        $('#dt_basic').on('click', ' tbody td .row-details', function () {
            var nTr = $(this).parents('tr')[0];
            if (oTable.fnIsOpen(nTr)) {
                $(this).addClass("fa-plus-square-o").removeClass("fa-minus-square-o");
                oTable.fnClose(nTr);
            }else {
                $(this).addClass("fa-minus-square-o").removeClass("fa-plus-square-o");;
                oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), 'details');
            }
        });

        $('#search').click(function(e){
            oTable.fnReloadAjax();
        });

        $('#modifyPwdForm').bootstrapValidator({
            excluded: [':disabled'],
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                oldPwd: {
                    validators: {
                        notEmpty: {
                            message: '旧密码不能为空'
                        }
                    }
                },
                newPwd: {
                    validators: {
                        notEmpty: {
                            message: '新密码不能为空'
                        }
                    }
                },
                confirmPassword: {
                    validators: {
                        notEmpty: {
                            message: '新密码不能为空'
                        }
                    }
                }
            }
        });

        $("#fileUpload").fileinput({
            uploadUrl:'rest/v1/sys/file/IMAGE?token='+Math.random(),
            allowedFileExtensions: ['jpg', 'png', 'gif'],
            overwriteInitial: false,
            maxFileSize: 10240,
            maxFilesNum: 1,
            enctype: 'multipart/form-data',
            showUpload: false,
            showCaption: false
        });

    });

    function fnFormatDetails(oTable, nTr) {
        var aData = oTable.fnGetData(nTr);
        var sOut = '<table style="margin:0px;padding: 0px;">';
        if(null != aData.headPortrait){
            var url = 'rest/v1/sys/file/image/'+aData.headPortrait ;
            sOut += '<tr><td rowspan="6" style="padding:0 10px 0 0;"><img src="'+url+'" width="128" height="128"/></td><td>用户名:</td><td>' + aData.name + '</td></tr>';
        }else{
            sOut += '<tr><td rowspan="6" style="padding:0 10px 0 0;"><img src="assets/img/avatars/default.jpg" width="128" height="128"/></td><td>用户名:</td><td>' + aData.name + '</td></tr>';
        }
        sOut += '<tr><td>昵称:</td><td>' + aData.alias + '</td></tr>';
        sOut += '<tr><td>邮件地址:</td><td><a href="mailto://abc@hm.com">'+aData.email+'</a></td></tr>';
        sOut += '<tr><td>手机号码:</td><td>' + aData.mobile + '</td></tr>';
        sOut += '<tr><td>创建时间:</td><td>' + TimeUtil.yyyyMMddHHmmss(aData.createTime) + '</td></tr>';
        sOut += '<tr><td>备注:</td><td>'+aData.note+'</td></tr>';
        sOut +='</table> ';
        return sOut;
    }

    function delData(id){
        layer.confirm('你真的要删除该数据吗?', {
            btn: ['删除','取消']
        }, function(index, layero){
            $.ajax({
                type:"DELETE",
                headers: {
                    "Content-Type": "application/json",
                    "X-HTTP-Method-Override": "DELETE"
                }, //PUT,DELETE
                url:"rest/v1/sys/user/"+window.atob(id),
                success:function(response){
                    layer.close(index);
                    Notify(response.message, 'top-right', '800', 'success', 'fa-bolt', true);
                    oTable.fnReloadAjax();
                },
                error: function(error) {
                    var obj = jQuery.parseJSON(error.responseText);
                    Notify(obj.message, 'top-right', '800', 'warning', 'fa-bolt', true);
                }
            });
        });
    }

    function modifyPwdDialog(id){
        document.modifyPwdForm.reset();
        layer.open({
            area: ['500px', '350px'],
            type: 1,
            title:'修改密码',
            content: $('#modifyPwdDialog'),
            btn: ['修改','取消'],
            yes: function(index, layero){
                var data = $('#modifyPwdForm').data('bootstrapValidator');
                if (data) {
                    data.validate();
                    if (data.isValid()) {
                        $.ajax({
                            type:"PUT",
                            url:"rest/v1/sys/user/pwd/"+window.atob(id)+"?oldPwd="+$('#oldPwd').val()+"&newPwd="+$('#newPwd').val(),
                            contentType: 'application/json',
                            dataType: 'json',
                            success:function(response){
                                layer.close(index);
                                Notify(response.message, 'top-right', '800', 'success', 'fa-bolt', true);
                            },
                            error: function(error) {
                                var obj = jQuery.parseJSON(error.responseText);
                                Notify(obj.message, 'top-right', '800', 'warning', 'fa-bolt', true);
                            }
                        });
                    }
                }
            }
        });
    }

    function modifyHptDialog(id){
        document.modifyHptForm.reset();
        layer.open({
            area: ['500px', '510px'],
            type: 1,
            title:'修改头像',
            content: $('#modifyHptDialog'),
            btn: ['修改','取消'],
            yes: function(index, layero){
                $.ajax({
                    url: 'rest/v1/sys/file/IMAGE?token='+Math.random() ,
                    type: 'POST',
                    data: new FormData($( "#modifyHptForm" )[0]),
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        modifyHpt(id,response.result,index);
                    },
                    error: function (response) {
                        alert(response);
                    }
                });
            }
        });
    }

    function modifyHpt(id,url,index){
        $.ajax({
            type:"PUT",
            url:"rest/v1/sys/user/hpt/"+window.atob(id)+"?url="+url,
            contentType: 'application/json',
            dataType: 'json',
            success:function(response){
                layer.close(index);
                Notify(response.message, 'top-right', '800', 'success', 'fa-bolt', true);
                oTable.fnReloadAjax();
            },
            error: function(error) {
                var obj = jQuery.parseJSON(error.responseText);
                Notify(obj.message, 'top-right', '800', 'warning', 'fa-bolt', true);
            }
        });
    }
</script>
